package com.metroinfo.workers.selector;

import java.io.IOException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

public class DispatcherN implements Dispatcher {

    private Selector sel;

    public DispatcherN() throws IOException {
	sel = Selector.open();
    }

    public void run() {
	for (;;) {
	    try {
		dispatch();
	    } catch (IOException x) {
		x.printStackTrace();
	    }
	}
    }

    private Object gate = new Object();

    private void dispatch() throws IOException {
	sel.select();
	for (Iterator<SelectionKey> i = sel.selectedKeys().iterator(); i.hasNext(); ) {
	    SelectionKey sk = i.next();
	    i.remove();
	    Handler h = (Handler)sk.attachment();
	    h.handle(sk);
	}
	synchronized (gate) { }
    }

    public void register(SelectableChannel ch, int ops, Handler h)
	    throws IOException {
	synchronized (gate) {
	    sel.wakeup();
	    ch.register(sel, ops, h);
	}
    }

} 